"use client"

import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Save, Plus, Trash2, Play } from "lucide-react"
import { useState } from "react"
import { useToast } from "@/hooks/use-toast"
import { mockData } from "@/lib/mock-data"
import { useRouter } from "next/navigation"

interface Endpoint {
  id: string
  name: string
  method: string
  path: string
  description: string
}

export default function CreateMCPPage() {
  const { toast } = useToast()
  const router = useRouter()
  const [endpoints, setEndpoints] = useState<Endpoint[]>([])

  const [formData, setFormData] = useState({
    name: "",
    version: "1.0.0",
    description: "",
    baseUrl: "",
    authType: "",
    authKey: "",
  })

  const addEndpoint = () => {
    setEndpoints([
      ...endpoints,
      {
        id: Date.now().toString(),
        name: "",
        method: "GET",
        path: "",
        description: "",
      },
    ])
  }

  const removeEndpoint = (id: string) => {
    setEndpoints(endpoints.filter((e) => e.id !== id))
  }

  const updateEndpoint = (id: string, field: keyof Endpoint, value: string) => {
    setEndpoints(endpoints.map((e) => (e.id === id ? { ...e, [field]: value } : e)))
  }

  const handleSave = () => {
    if (!formData.name || !formData.description) {
      toast({
        title: "错误",
        description: "请填写 MCP 名称和描述",
        variant: "destructive",
      })
      return
    }

    mockData.addMCP({
      name: formData.name,
      description: formData.description,
      status: "connected",
      version: formData.version,
      lastSync: "刚刚",
      endpoints: endpoints.length,
    })

    toast({
      title: "MCP 已创建",
      description: `${formData.name} 已成功创建`,
    })

    router.push("/dashboard/mcp")
  }

  const handleTest = () => {
    toast({
      title: "测试中",
      description: "正在测试 MCP 连接...",
    })
    setTimeout(() => {
      toast({
        title: "测试成功",
        description: "MCP 连接正常",
      })
    }, 1500)
  }

  return (
    <AuthGuard>
      <DashboardLayout>
        <div className="max-w-4xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold tracking-tight">创建自定义 MCP</h1>
              <p className="text-muted-foreground mt-2">定义您自己的模型上下文协议</p>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={handleTest}>
                <Play className="mr-2 h-4 w-4" />
                测试
              </Button>
              <Button onClick={handleSave}>
                <Save className="mr-2 h-4 w-4" />
                保存
              </Button>
            </div>
          </div>

          {/* Basic Info */}
          <Card>
            <CardHeader>
              <CardTitle>基本信息</CardTitle>
              <CardDescription>配置 MCP 的基本属性</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="name">MCP 名称</Label>
                  <Input
                    id="name"
                    placeholder="我的自定义 MCP"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="version">版本</Label>
                  <Input
                    id="version"
                    placeholder="1.0.0"
                    value={formData.version}
                    onChange={(e) => setFormData({ ...formData, version: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="description">描述</Label>
                <Textarea
                  id="description"
                  placeholder="描述这个 MCP 的功能..."
                  className="min-h-[80px] resize-none"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="baseUrl">基础 URL</Label>
                <Input
                  id="baseUrl"
                  placeholder="https://api.example.com"
                  value={formData.baseUrl}
                  onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
                />
              </div>
            </CardContent>
          </Card>

          {/* Authentication */}
          <Card>
            <CardHeader>
              <CardTitle>认证配置</CardTitle>
              <CardDescription>设置 API 认证方式</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="authType">认证类型</Label>
                <Input
                  id="authType"
                  placeholder="Bearer Token / API Key / OAuth"
                  value={formData.authType}
                  onChange={(e) => setFormData({ ...formData, authType: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="authKey">认证密钥</Label>
                <Input
                  id="authKey"
                  type="password"
                  placeholder="输入 API 密钥..."
                  value={formData.authKey}
                  onChange={(e) => setFormData({ ...formData, authKey: e.target.value })}
                />
              </div>
            </CardContent>
          </Card>

          {/* Endpoints */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>端点配置</CardTitle>
                  <CardDescription>定义 MCP 提供的 API 端点</CardDescription>
                </div>
                <Button onClick={addEndpoint} size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  添加端点
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {endpoints.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <p>还没有添加端点</p>
                  <p className="text-sm mt-1">点击上方按钮添加第一个端点</p>
                </div>
              ) : (
                <ScrollArea className="h-[400px]">
                  <div className="space-y-4">
                    {endpoints.map((endpoint, index) => (
                      <Card key={endpoint.id}>
                        <CardHeader className="pb-3">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-medium">端点 {index + 1}</span>
                              <Badge variant="outline">{endpoint.method || "GET"}</Badge>
                            </div>
                            <Button variant="ghost" size="icon" onClick={() => removeEndpoint(endpoint.id)}>
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-3">
                          <div className="grid gap-3 md:grid-cols-2">
                            <div className="space-y-2">
                              <Label>端点名称</Label>
                              <Input
                                placeholder="getUserInfo"
                                value={endpoint.name}
                                onChange={(e) => updateEndpoint(endpoint.id, "name", e.target.value)}
                              />
                            </div>
                            <div className="space-y-2">
                              <Label>请求方法</Label>
                              <Input
                                placeholder="GET"
                                value={endpoint.method}
                                onChange={(e) => updateEndpoint(endpoint.id, "method", e.target.value)}
                              />
                            </div>
                          </div>
                          <div className="space-y-2">
                            <Label>路径</Label>
                            <Input
                              placeholder="/api/users/:id"
                              value={endpoint.path}
                              onChange={(e) => updateEndpoint(endpoint.id, "path", e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label>描述</Label>
                            <Input
                              placeholder="获取用户信息"
                              value={endpoint.description}
                              onChange={(e) => updateEndpoint(endpoint.id, "description", e.target.value)}
                            />
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </ScrollArea>
              )}
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </AuthGuard>
  )
}
